package com.dding.cms.base.web.widget.handler;

import static com.dding.cms.base.web.ActionConstants.CHANNEL_ID;
import static com.dding.cms.base.web.ActionConstants.CHANNEL_TABLE_NAME;
import static com.dding.cms.base.web.ActionConstants.DEFAULT_CHANGE_FIELDS;
import static com.dding.cms.base.web.ActionConstants.UPDATE_DATA_MAP;
import static com.dding.cms.base.web.ActionConstants.WIDGET_REMOVE_ID_KEY;
import static com.dding.cms.base.web.ActionConstants.WIDGET_RESULT_KEY;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.dding.core.util.StringUtils;
import org.javalite.activejdbc.Model;

import com.dding.cms.base.entity.Channel;
import com.dding.cms.base.entity.Content;
import com.dding.cms.base.web.widget.IWidgetContext;
import com.dding.cms.base.web.widget.WidgetTable;

@WidgetTable(CHANNEL_TABLE_NAME)
public class ContentChannelHandler extends AbstractWidgetHandler {

	@Override
	public Object handleSet(IWidgetContext widgetContext) {

		List<Model> list = new ArrayList<Model>();
		List<String> ids = new ArrayList<String>();

		Map<String, Object> parameter = widgetContext.getParameters();

		Map<String, Object> result = new HashMap<String, Object>();
		result.put(WIDGET_RESULT_KEY, list);
		result.put(WIDGET_REMOVE_ID_KEY, ids);

		String[] value = getParameterSetValue(CHANNEL_ID, null, parameter, null);
		if (value == null || value.length == 0 || StringUtils.isEmpty(value[0])) {
			return result;
		}
		Model channel = Channel.findById(value[0]);
		list.add(channel);
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object handleUpdateAssociation(IWidgetContext widgetContext) {

		Map<String, Object> data = widgetContext.getParameters();

		Map<String, Object> dataMap = (Map<String, Object>) data
				.get(UPDATE_DATA_MAP);

		String content_id = ((String[]) dataMap.get("content_id"))[0];

		Model content = Content.findById(content_id);

		String[] value = getParameterSetValue(CHANNEL_ID, null, dataMap, null);
		if (value == null || value.length == 0 || StringUtils.isEmpty(value[0])) {
			return null;
		}
		Integer channel_id = content.getInteger(CHANNEL_ID);
		if (channel_id.toString().equals(value[0])) {
			return null;
		}
		Content.update("channel_id = ?", "content_id = ?", new Object[] {
				value[0], content_id });

		Model channel = Channel.findById(value[0]);
		content.remove(Channel.findById(channel_id));
		content.add(channel);

		return null;
	}
}
